<?php

declare(strict_types=1);

namespace App\Services;

use Illuminate\Support\Facades\Log;

class HttpService
{
    /**
     * @return bool|string
     */
    public static function curlGet(string $url)
    {
        Log::info('curlGet url ' . $url);

        $headers = [
            'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36',
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $output   = curl_exec($ch); // json格式
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($httpCode != 200) {
            Log::warning(__METHOD__ . ':httpCode:' . $httpCode . '');
        }
        curl_close($ch);
        Log::info('curlGet resp: ' . $output);

        return $output;
    }

    /**
     * @return bool|string
     */
    public static function curlPost(string $url, array $post)
    {
        Log::info('curlPost data', $post);

        $c = curl_init();
        curl_setopt($c, CURLOPT_URL, $url);
        curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($c, CURLOPT_TIMEOUT, 30);
        curl_setopt($c, CURLOPT_HEADER, 0);
        curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($c, CURLOPT_POSTFIELDS, json_encode($post));
        $res      = curl_exec($c);
        $httpCode = curl_getinfo($c, CURLINFO_HTTP_CODE);
        if ($httpCode != 200) {
            Log::warning(__METHOD__ . ':httpCode:' . $httpCode . '');
        }
        curl_close($c);
        Log::info('curlPost resp: ' . $res);

        return $res;
    }
}
